from artSightWorld.apps.base.models import *
from artSightWorld.apps.base.views import *
from artSightWorld.apps.addPhotos.forms import *
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.core.files.images import ImageFile
import StringIO
from PIL import Image, ImageOps
import os
from django.core.files import File
from datetime import *
from django.http import *


def addAlbum(request):
	if (request.user.is_authenticated()):
		if request.method == 'POST': # If the form has been submitted...
			form = AddAlbumForm(request.POST) # A form bound to the POST data
			if form.is_valid(): 
				album = Album(photographer_id = request.user.pk, nom = form.cleaned_data['nom'])
				album.save()
				
				form = AddPhotosForm(initial={'album': album, 'userId': request.user.pk})
				return render_to_response('addPhotos/addPhotos.html', {'form': form, 'error_message':'Album ajoute ! Vous pouvez maintenant y ajouter des photos'}, context_instance=RequestContext(request) )
			else:
				form = AddAlbumForm()
				return render_to_response('addPhotos/addAlbum.html', {'form': form, 'error_message' : 'Echec lors de l\'ajout de l\'album'}, context_instance=RequestContext(request) )
		else :
			form = AddAlbumForm()
			return render_to_response('addPhotos/addAlbum.html', {'form': form, 'message':''}, context_instance=RequestContext(request) )
	else:
		home(request)

def addPhotos(request):
	if (request.user.is_authenticated()):
		if request.method == 'POST': # If the form has been submitted...
			form = AddPhotosForm(request.POST, request.FILES, initial={'userId': request.user.pk}) # A form bound to the POST data
			if form.is_valid(): 
				
				imageForm = request.FILES['image']

				city = City.objects.get(pk=form.cleaned_data['city_id'])
				photo = Photo(height=10, width=10, latitude=city.latitude, longitude=city.longitude, dateTaken=form.cleaned_data['dateTaken'], city_id=city.pk, album_id=form.cleaned_data['album'].pk, title=form.cleaned_data['titre'], caption=form.cleaned_data['caption'], banned=0)
				photo.image.save(imageForm.name, imageForm)
				photo.height = photo.image.height			 
				photo.width =  photo.image.width
				
				photo.save()

				handle_uploaded_image(request.FILES['image'], photo.image.height, photo.image.width, imageForm.name)

				form = AddPhotosForm(initial={'userId': request.user.pk})
				return render_to_response('addPhotos/addPhotos.html', {'form': form, 'error_message':'Photo ajoutee ! Vous pouvez en ajouter une nouvelle'}, context_instance=RequestContext(request) )
			else:
				
				return render_to_response('addPhotos/addPhotos.html', {'form': form, 'error_message' : 'Echec lors de l\'ajout de la photo'}, context_instance=RequestContext(request) )
		else :
			form = AddPhotosForm(initial={'userId': request.user.pk})
			return render_to_response('addPhotos/addPhotos.html', {'form': form, 'message':''}, context_instance=RequestContext(request) )
	else:
		home(request)
		
def handle_uploaded_image(i, width, height, name):

	str = ""
	for c in i.chunks():
		str += c

	# create PIL Image instance
	imagefile  = StringIO(str)
	image = Image.open(imagefile)
	thumbImage = image.resize((170,int(width * 170 / float(height))))
	
	thumbImage.save('media/uploads/thumb/'+name)

def checkCity (request, cityName):
	cities = City.objects.filter(name=str(cityName))
	content = "<liste>\n"
	for city in cities :
		content = content + "<city name=\"" + city.name + " (" + city.region.country.name +")\" latitude=\"" + str(city.longitude) +"\" longitude=\"" + str(city.latitude) + "\" city_id=\"" + str(city.pk) + "\" />\n";
	content = content + "</liste>"
	response = HttpResponse(content, mimetype="application/xml")
	return response